<template>
  <div :style="{width: '98%', height: height+'px',border:'1px solid #DCDFE6',borderRadius: '3px'}" ref="editor" id="editor"></div>
</template>

<script>
import * as monaco from 'monaco-editor';
import {MysqlKeywords} from "./keyword.js";
import { format } from "sql-formatter";

export default {
  name: "BMonacoEditor",
  props: {
    editable: { type: Boolean, default: true },
    language: { type: String, default: "plaintext" },
    value: { type: String, default: "" },
    height: { type: Number, default: 300 },
  },

  data() {
    return {
      editor: null,
    };
  },

  // created() {
  //     let src =
  //     "https://microsoft.github.io/monaco-editor/node_modules/monaco-editor/min/vs/loader.js";
  //   this.toCreateScript(src);
  //   // this.toCreate()
  // },

  mounted() {
    // this.editor = monaco.editor.create(document.getElementById('editor'), {
    //   value: 'console.log("Hello, World!");',
    //   language: 'javascript'
    // });
    this.toCreate()
  },

  watch: {
    value: function (val) {
      if (val) {
        this.updateEditor(val);
      } else {
        this.editor.setValue("");
      }
    },
    editable:{
      handler(val){
        if (val) {
          this.editor.updateOptions({readOnly:val})
        } else {
          this.editor.updateOptions({readOnly:false})
        }
       
      },
      deep: true
    }
  },

  methods: {
    // loader() {
    //   let require = window.require;
    //   let vsPath =
    //     "https://microsoft.github.io/monaco-editor/node_modules/monaco-editor/min/vs";
    //   require.config({ paths: { vs: vsPath } });
    //   require(["vs/editor/editor.main"], () => this.toCreate());
    // },

   async toCreate () {
      // if (!this.editor) {
      const { value } = this;
      await monaco.languages.registerCompletionItemProvider('sql', {
        provideCompletionItems: function (model, position) {
          const line = position.lineNumber;
          const column = position.column;
          const content = model.getLineContent(line)
          const sym = content[column - 2];
          let word = model.getWordUntilPosition(position);
          let range = {
            startLineNumber: position.lineNumber,
            endLineNumber: position.lineNumber,
            startColumn: word.startColumn,
            endColumn: word.endColumn
          };
          let suggestions = [];
          if (sym === "$") {
          } else {
            let sqlStr = MysqlKeywords
            for (let i in sqlStr) {
              suggestions.push({
                label: sqlStr[i],
                kind: monaco.languages.CompletionItemKind['Function'],
                insertText: sqlStr[i],
                detail: '',
                range: range
              });
            }
          }
          return {
            suggestions: suggestions
          };
        },
        triggerCharacters: ["$", ""]
      });
      this.editor = monaco.editor.create(this.$refs.editor, {
        value,
        language: "sql",
        lineNumbers: 'off',
        roundedSelection: false,
        scrollBeyondLastLine: false,
        readOnly: this.editable,
        theme: 'vs',
        automaticLayout: true,
        wordWrap: 'wordWrapColumn',
        // wordWrapColumn: 100,
        // Set this to false to not auto word wrap minified files
        wordWrapMinified: true,
        // try "same", "indent" or "none"
        wrappingIndent: 'indent',
        scrollbar: {
          // Subtle shadows to the left & top. Defaults to true.
          useShadows: false,
          // Render vertical arrows. Defaults to false.
          verticalHasArrows: false,
          // Render horizontal arrows. Defaults to false.
          horizontalHasArrows: false,
          // Render vertical scrollbar.
          // Accepted values: 'auto', 'visible', 'hidden'.
          // Defaults to 'auto'
          vertical: 'auto',
          // Render horizontal scrollbar.
          // Accepted values: 'auto', 'visible', 'hidden'.
          // Defaults to 'auto'
          horizontal: 'auto',
          verticalScrollbarSize: 10,
          horizontalScrollbarSize: 10,
          arrowSize: 10,
        },
        minimap: {
          enabled: false
        }
      });
      const beautyFunc = {
        id: "ms-beauty",
        label: "SQL Format",
        keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_B],
        contextMenuGroupId: "navigation",
        contextMenuOrder: 1.5,
        run: ed => {
          try {
            const sql = format(ed.getValue());
            ed.setValue(sql);

            this.$emit("format", sql);
          } catch (error) {
            // console.log(error);
          }
        }
      };
      this.editor.addAction(beautyFunc);
      this.editor.onDidChangeModelContent(() => {
        this.$emit("input", this.editor.getValue());
      });
      this.updateEditor(this.value);
      // }
    },

    // toCreateScript(src) {
    //   let head = document.querySelector("head");
    //   let script = document.createElement("script");
    //   script.onload = () => this.loader();
    //   script.onerror = () => {
    //     head.removeChild(script);
    //   };
    //   script.src = src;
    //   head.appendChild(script);
    // },

    updateEditor(content) {
      let contentstr = ''
      let contentstrParams = ''
      if (content) {
        contentstr = content.replace(/\{\s+/g, "{").replace(/\s+\}/g, "}");
      }
      contentstrParams = contentstr ? contentstr : content
      if (this.editor) {
        if (contentstrParams != this.editor.getValue()) this.editor.setValue(contentstrParams);
        // select * from bot_message_old_token_logs where {tenant_code} = {tenant_code}
      }
     
    },
  },
  beforeDestroy() {
    this.editor && this.editor.dispose();
  }
};
</script>
